import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/pages/common/five_start_rating_widget.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';

class CourseReviewListCellWidget extends StatefulWidget {
  final int courseId;
  final bool isMycourse;
  final bool isMyReview;
  final CourseReview review;

  const CourseReviewListCellWidget({
    required this.courseId,
    required this.isMycourse,
    this.isMyReview = false,
    required this.review,
    super.key,
  });

  @override
  State<CourseReviewListCellWidget> createState() =>
      _CourseReviewListCellWidgetState();
}

class _CourseReviewListCellWidgetState
    extends State<CourseReviewListCellWidget> {
  late final CourseReview review;

  @override
  void initState() {
    super.initState();
    review = widget.review;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildReviewTitleRow(context),
          const SizedBox(height: 10),
          _buildContentRow(context),
          const SizedBox(height: 10),
          _buildReviewTimeRow(context),
          _buildReplyWidget(context),
          _buildAuthorActionWidget(context),
        ],
      ),
    );
  }

  // 评论时间
  Widget _buildReviewTimeRow(BuildContext context) {
    final text = DateFormat('yyyy-MM-dd kk:mm').format(review.reviewAt);
    return SizedBox(
      width: double.infinity,
      child: Text(
        text,
        textAlign: TextAlign.right,
        style: Theme.of(context).textTheme.bodySmall,
      ),
    );
  }

  // 评论内容
  Widget _buildContentRow(BuildContext context) {
    return Text(
      review.content,
      style: Theme.of(context).textTheme.bodyMedium?.copyWith(height: 1.75),
    );
  }

  // 评论人
  Widget _buildReviewTitleRow(BuildContext context) {
    final title = widget.isMyReview ? AppStrings.myReview : review.userName;
    return Row(
      children: [
        Expanded(
          child: Text(
            title,
            style: Theme.of(
              context,
            ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
          ),
        ),
        const SizedBox(width: 8),
        FiveStartRatingWidget(rating: review.rating, starSize: 16),
      ],
    );
  }

  // 老师回复
  Widget _buildReplyWidget(BuildContext context) {
    if (review.reply == null) {
      return const SizedBox.shrink();
    } else {
      final span1 = TextSpan(
        text: AppStrings.teacherReply,
        style: Theme.of(
          context,
        ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
      );
      final span2 = TextSpan(
        text: review.reply,
        style: Theme.of(context).textTheme.bodyMedium?.copyWith(height: 1.75),
      );
      return Column(
        children: [
          const SizedBox(height: 10),
          RichText(text: TextSpan(children: [span1, span2])),
        ],
      );
    }
  }

  // 编辑评论
  Widget _buildAuthorActionWidget(BuildContext context) {
    if (widget.isMycourse) {
      final v = review.reply == null;
      final text = v ? AppStrings.reply : AppStrings.editReply;
      return Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          const SizedBox(height: 6, width: double.infinity),
          TextButton(
            onPressed: () {
              context
                  .pushNamed<String?>(
                    AppRouter.kCourseReviewReply,
                    queryParameters: {
                      'id': review.id.toString(),
                      'course_id': widget.courseId.toString(),
                      'rating': review.rating.toString(),
                      'user': review.userName,
                      'content': review.content,
                      'reply_id': review.replyId?.toString() ?? '',
                      'reply_content': review.reply ?? '',
                    },
                  )
                  .then((value) {
                    if (value != null && value.isNotEmpty) {
                      setState(() {
                        review.reply = value;
                      });
                    }
                  });
            },
            child: Text(text),
          ),
        ],
      );
    } else if (widget.isMyReview) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          const SizedBox(height: 6, width: double.infinity),
          TextButton(
            onPressed: () {
              context
                  .pushNamed<CourseReview?>(
                    AppRouter.kCourseReview,
                    queryParameters: {
                      'course_id': widget.courseId.toString(),
                      'rating': review.rating.toString(),
                      'review_content': review.content,
                    },
                  )
                  .then(
                    (r) => {
                      if (r != null)
                        {
                          setState(() {
                            review.rating = r.rating;
                            review.content = r.content;
                          }),
                        },
                    },
                  );
            },
            child: Text(AppStrings.editReview),
          ),
        ],
      );
    } else {
      return const SizedBox.shrink();
    }
  }
}
